#include "client.h"
extern int pipefds[2];
extern char login_name[50];
int login (int peerfd){
    train_t t;
    memset(&t,0,sizeof(t));

    login1(peerfd,&t);
    login2(peerfd,&t);
    return 0;
}

void login1(int peerfd, train_t * t){
    
    train_t train;
    memset(&train , 0 ,sizeof(train));
    //接受并发送用户名

    while(1){
        printf("please enter your username:");
        char name[512] = {0};
        scanf("%s",name);
        
        //初始化小火车并发送
        train.len = strlen(name);
        train.type = CMD_TYPE_LOGIN1;
        strcpy(train.buff,name);
        //更新全局变量，记录发送给子线程的名字
        strcpy(login_name,name);
        sendn(peerfd,&train,4+4+train.len);
        printf("login1 send %d byte\n",train.len);

        //接受server生成的salt值,TODO
        memset(&train,0,sizeof(train));
        int len = 0;
        CmdType x;
        recvn(peerfd,&len,sizeof(len));
        recvn(peerfd,&x,sizeof(x));
        recvn(peerfd,train.buff,len);
        if(x == CMD_TYPE_LOGIN1_ERROR){
            puts("username does not exist!");
        }else{
            memcpy(t,&train,sizeof(train));
            break;
        }
    }
}
void login2(int peerfd, train_t * t){
    train_t train;
    memset(&train , 0 ,sizeof(train));
    //经由crypt函数获得密文 --编译时要加上-lcrypt库

    while(1){
        printf("please enter your password:");
        char password[512] = {0};
        scanf("%s",password);

        //获得client端产生的encrypt
        char encrypt[512] = {0};
        char * a = crypt(password,t->buff);
        int len = strlen(a);
        memcpy(encrypt,a,len);
        //初始化小火车并发送
        memset(&train, 0, sizeof(train));
        train.len = len;
        train.type = CMD_TYPE_LOGIN2;
        strcpy(train.buff,encrypt);
        sendn(peerfd,&train,4+4+train.len);
        printf("login2 send %d byte\n",train.len);

        //接受server经由对比得到的正确与否消息
        memset(&train,0,sizeof(train));
        len = 0;
        CmdType x;
        recvn(peerfd,&len,sizeof(len));
        recvn(peerfd,&x,sizeof(x));
        recvn(peerfd,train.buff,len);
        if(x == CMD_TYPE_LOGIN2_ERROR){
            puts("wrong password!");
        }else{
            memset(&train,0,sizeof(train));
            train.len = strlen(login_name);
            train.type = CMD_TYPE_LOGIN_PIPE;
            strcpy(train.buff,login_name);
            //发送给子线程已经登录的用户名
            write(pipefds[1],&train.len,4);
            write(pipefds[1],&train.type,4);
            write(pipefds[1],&train.buff,train.len);
            puts("登录成功");
            break;
        }
    }
}

